package cn.base.web.support.file;

import cn.rengy.tool.excel.ExcelWriteBuilder;
import cn.rengy.tool.excel.ExcelWriterSheetBuilder;
import cn.rengy.tool.excel.HeaderCellObject;
import cn.rengy.util.ExceptionPrintUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

@Slf4j
public class ExcelWriteUtil {

    /**
     * 写文件
     */
    public static  void writeExcel(File saveDir,File excelFile, PageDataService<List<Map<String,Object>>> pageDataService){


        try(OutputStream outputStream=new FileOutputStream(excelFile);){
            ExcelWriteBuilder excelWriterBuilder = new ExcelWriteBuilder(outputStream);
            ExcelWriterSheetBuilder excelWriterSheetBuilder= excelWriterBuilder.sheet(null);
            Map<Integer, HeaderCellObject> header=( Map<Integer, HeaderCellObject>)pageDataService.getHeader();
            excelWriterSheetBuilder.setHeaderData(header);
            //分页查询导出数据
            int pageSize=10000;
            List<Map<String,Object>> list=null;
            PageRequest pageRequest=PageRequest.ofSize(pageSize);
            do {
                list= pageDataService.getPage(pageRequest);
                pageRequest=pageRequest.next();
                if(list!=null&& !list.isEmpty()){
                    excelWriterSheetBuilder.doSimpleWrite(list);
                }
            }while (list!=null&& !list.isEmpty());

            excelWriterBuilder.finish();
        }catch (Exception e) {
            log.error(ExceptionPrintUtils.getTrace(e));
        }
    }
}
